<template>
	<yb-page allowScroll :style="{'background-color': skinColor.color_bg_1}">
		<view class="yb-flex nav-bar-box" :style="{
			'background-color': skinColor.color_bg_1,
			'border-bottom-color': skinColor.color_gap_1
		}">
			<yb-status-bar color="rgba(0,0,0,.5)"></yb-status-bar>
			<view class="nav-bar yb-flex yb-row yb-align-center padding-gap" elevation="1px">
				<yb-tap @click="app.$Router.back()">
					<yb-icon name="arrow-left" :color="skinColor.color_1" size="50"></yb-icon>
				</yb-tap>
				<view class="yb-flex yb-flex-1 yb-row yb-align-center">
					<yb-text custom-style="margin-left: 30rpx" weight="bold" line-height="35" size="35" :color="skinColor.color_1" :value="app.$business.getType(type) + '详情'"></yb-text>
					<!-- <yb-tag plain custom-style="margin-left: 20rpx" :options="{
						bgColor: skinColor.color_red,
						size: 20
					}" :value="app.$business.filterSource(source).title"></yb-tag> -->
					<yb-tap @click="app.$business.toCollection(params)" custom-style="margin-left: 20rpx;">
						<yb-tag plain :value="app.$business.isCollection(id) ? '已收藏' : '收藏'" :options="{
							'bgColor': app.$business.isCollection(id) ? skinColor.color_3 : skinColor.color_blue,
							'radius': 30,
							'size': 20
						}"></yb-tag>
					</yb-tap>
					<yb-tap @click="jumpPage" v-if="params.catalogUrl" custom-style="margin-left: 20rpx;">
						<yb-tag plain value="跳转" :options="{
							'bgColor': skinColor.color_red,
							'radius': 30,
							'size': 20
						}"></yb-tag>
					</yb-tap>
				</view>
				<yb-tap custom-style="margin-left: 15rpx" @click="handleCopyClick">
					<rd-icon name="search" :color="skinColor.color_1" :size="44"></rd-icon>
				</yb-tap>
				<yb-tap custom-style="margin-left: 15rpx" @click="app.$business.shareWeb(params)">
					<rd-icon name="share-rect" :color="skinColor.color_1" :size="40"></rd-icon>
				</yb-tap>
			</view>
		</view>
		<rd-recomes
		ref="comment"
		:list="comments"
		:recomes="recomes">
			<yb-list-item>
				<view class="yb-flex">
					<yb-status-bar></yb-status-bar>
					<yb-gap :size="100"></yb-gap>
				</view>
				<view class="padding-gap yb-flex">
					<yb-gap></yb-gap>
					<yb-text weight="bold" :size="40" :lineHeight="60" :color="skinColor.color_1" :value="title" v-if="title"></yb-text>
					<view class="yb-flex yb-row yb-align-center yb-justify-between" style="margin-top: 10rpx;">
						<yb-text size="23" :color="skinColor.color_3" :value="updateTime || app.$utils.dateFormat(new Date().getTime())"></yb-text>
						<yb-text size="23" :color="skinColor.color_3" :value="'编辑：' + (creator || '佚名')"></yb-text>
						<yb-text size="23" :color="skinColor.color_3" :value="'类型：' + (style || app.$business.getType(type))"></yb-text>
					</view>
					<yb-text custom-style="margin-top:20rpx" v-if="desc" :size="28" :color="skinColor.color_3" :value="desc"></yb-text>
					<view class="tags yb-flex yb-row yb-wrap" v-if="tags.length > 0">
						<yb-tap @click="app.$Router.push({
							path: '/pages/search/result',
							query: {
								keyword: tag,
								type: type
							}
						})" custom-style="margin-right: 10rpx;margin-bottom: 10rpx;" v-for="(tag, i) in tags" :key="i">
							<yb-tag :options="{
								bgColor: skinColor.color_3,
								color: skinColor.color_white
							}" :value="tag"></yb-tag>
						</yb-tap>
					</view>
					<rd-character style="margin-top: 30rpx;" v-if="characters.length > 0" :list="characters"></rd-character>
				</view>
			</yb-list-item>
			<yb-list-item>
				<view class="rd-community yb-flex" :style="{
					'border-bottom-color': skinColor.color_gap_1
				}">
					<view class="content" @longpress="copyTo(params.content)">
						<text v-if="params.content" :style="'color: ' + skinColor.color_1 + '!important;'" v-html="convertHTML(params.content)"></text>
					</view>
				</view>
			</yb-list-item>
			<template v-if="recomes.length > 0">
				<yb-list-item>
					<yb-gap size="10" :color="skinColor.color_gap_1"></yb-gap>
					<yb-gap></yb-gap>
					<view class="yb-flex yb-row yb-align-center margin-gap">
						<view class="title-dot" :style="{
							'background-color': skinColor.color_cyan
						}"></view>
						<yb-text :color="skinColor.color_1" size="30" weight="bold" value="相关推荐"></yb-text>
					</view>
					<yb-gap></yb-gap>
				</yb-list-item>
			</template>
			<template #center>
				<yb-list-item v-if="catalogs.length > 0">
					<yb-gap size="10" custom-class="more_content" :color="skinColor.color_gap_1"></yb-gap>
					<yb-gap></yb-gap>
					<view class="yb-flex yb-row yb-align-center margin-gap">
						<view class="title-dot" :style="{
							'background-color': skinColor.color_cyan
						}"></view>
						<yb-text :color="skinColor.color_1" size="30" weight="bold" value="更多内容"></yb-text>
					</view>
					<yb-gap></yb-gap>
				</yb-list-item>
				<yb-list-item v-for="(item, index) in catalogs" :key="item.id + '_' + index + '_' + item.type">
					<view class="rd-community yb-flex" :style="{
						'border-bottom-color': skinColor.color_gap_1
					}">
						<view class="subtitle yb-flex yb-row yb-align-center">
							<yb-avatar class="cover" :size="80" :src="item.avatar || app.$business.getDefaultAvatar(item.source)"></yb-avatar>
							<view class="info yb-flex yb-flex-1">
								<yb-text custom-class="title" :lines="1" :size="30" :color="skinColor.color_1" :value="item.creator || app.$business.filterSource(item.source).title"></yb-text>
								<yb-text custom-class="time" :lines="1" :size="24" :color="skinColor.color_3" :value="item.updateTime || item.title || '第' + (index + 1) + '楼'"></yb-text>
							</view>
							<text class="land" :style="{color: skinColor.color_3}"># {{index + 1}}</text>
						</view>
						<view class="content" @longpress="copyTo(item.content || item.desc)">
							<view v-if="item.content" :style="'color: ' + skinColor.color_1 + '!important;'" v-html="convertHTML(item.content)"></view>
							<text class="content-text" :style="{color: skinColor.color_1}" v-else>{{item.desc}}</text>
						</view>
						<!-- <view class="images">
							<yb-grid :data="item.list" :gap="20" :column="5">
								<template v-for="(image, i) in item.list" :slot="i">
									<view class="image yb-flex" @click="onItemClick(image)">
										<rd-image tipSize="34" lazyLoad :border-radius="10" class="yb-flex-1" :src="image.type ? app.$business.getCover(image) : image" mode="aspectFill"></rd-image>
										<text v-if="image.type" class="badge" :style="{
											'background-color': app.$business.getColor(image.type),
											color: skinColor.color_white
										}">{{app.$business.getType(image.type)}}</text>
									</view>
								</template>
							</yb-grid>
						</view>
						<view class="comments yb-flex" v-if="item.comments.length > 0" :class="{
							'comments-none': item.comments.length == 0
						}" :style="{'background-color': skinColor.color_gap_1}">
							<view class="comment" v-for="(comment, i) in item.comments.slice(0, 2)" :key="i">
								<text class="comment-label" :style="{color: skinColor.color_blue}">{{comment.title}}：</text>
								<text class="comment-content" :style="{color: skinColor.color_1}">{{comment.content}}</text>
							</view>
							<view class="comment-more yb-flex yb-row yb-align-center yb-justify-center" v-if="item.comments.length > 2" @tap="app.$business.showComment(item)">
								<text class="comment-more-text" :style="{color: skinColor.color_cyan}">查看更多评论</text>
								<yb-icon name="angle-arrow-down" :size="26" :color="skinColor.color_cyan"></yb-icon>
							</view>
						</view> -->
						<view class="yb-flex yb-row yb-align-center yb-justify-end" style="margin-top: 20rpx;" v-if="item.commentUrl">
							<!-- <view class="tip yb-flex yb-row yb-align-center" @tap="onCharacterClick(item)" v-if="item.characterUrl">
								<rd-icon name="avatar" size="30" :color="skinColor.color_3"></rd-icon>
								<text class="tip-text" :style="{color: skinColor.color_3}">看用户</text>
							</view>
							<view class="tip-gap" :style="{'background-color': skinColor.color_3}" v-if="item.commentUrl && item.characterUrl"></view> -->
							<view class="tip yb-flex yb-row yb-align-center" @tap="app.$business.showComment(item)" v-if="item.commentUrl">
								<rd-icon name="comment" size="30" :color="skinColor.color_3"></rd-icon>
								<text class="tip-text" :style="{color: skinColor.color_3}">看评论</text>
							</view>
						</view>
					</view>
				</yb-list-item>
				<yb-list-item v-if="comments.length > 0">
					<yb-gap size="10" :color="skinColor.color_gap_1"></yb-gap>
					<yb-gap></yb-gap>
					<view class="yb-flex yb-row yb-align-center margin-gap">
						<view class="title-dot" :style="{
							'background-color': skinColor.color_cyan
						}"></view>
						<yb-text :color="skinColor.color_1" size="30" weight="bold" value="评论列表"></yb-text>
					</view>
					<yb-gap></yb-gap>
				</yb-list-item>
			</template>
			<template #bottom>
				<yb-list-item>
					<view class="loadmore yb-flex yb-row yb-align-center yb-justify-center">
						<yb-loading custom-style="margin-right: 20rpx" :visible="commentLoadmore || loadmore" size="26" :color="skinColor.color_1"></yb-loading>
						<yb-text size="26" :color="skinColor.color_1" :value=" commentIsLastPage && isLastPage ? '~~ 后面已经没有了 ~~' : '正在加载' + (commentLoadmore ? '更多评论' : '更多内容')"></yb-text>
					</view>
				</yb-list-item>
			</template>
		</rd-recomes>
		<view class="loading yb-flex yb-align-center yb-justify-center" :style="{
			'background-color': skinColor.color_bg_1
		}" v-if="loading">
			<yb-loading :visible="loading" :color="skinColor.color_1" size="40" text="正在加载中"></yb-loading>
		</view>
		<yb-dialog ref="dialog"></yb-dialog>
		<yb-action-sheet ref="actionSheet"></yb-action-sheet>
	</yb-page>
</template>

<script>
	import appMixin from '@/common/mixin/app.js';
	import paramsMixin from '@/common/mixin/params.js'
	import detailMixin from '@/common/mixin/detail.js';
	import commentMixin from '@/common/mixin/comment.js';
	import HTMLParser from "@/uni_modules/html-parser/js_sdk/index.js"
	export default {
		mixins: [appMixin, paramsMixin, detailMixin, commentMixin],
		computed: {
			record () {
				const index = this.$store.getters['record/get'].findIndex(record => record.id == this.id)
				return index > -1 ? this.$store.getters['record/get'][index] : null
			}
		},
		data () {
			return {
				nextUrl: '',
				currentPage: 1,
				loadmore: false,
				isLastPage: false
			}
		},
		onReady() {
			this.loading = true
			this.$nextTick(function () {
				setTimeout(() => {
					if ( this.record && this.record.current && this.record.current > 1 ) {
						this.$refs.dialog.confirm({
							title: {
								color: this.skinColor.color_1,
								text: '跳转提示'
							},
							content: {
								color: this.skinColor.color_1,
								text: '上次阅读到第' + this.record.current + '页，是否跳转并跳过前' + (this.record.current - 1) + '页？\n\n点击确认跳转'
							},
							options: {
								bgColor: this.skinColor.color_bg_2
							},
							success: ret => {
								if ( ret.confirm ) this.currentPage = this.record.current
								this.handlePulldown()
							}
						})
					} else{ this.handlePulldown() }
				}, 500)
			})
		},
		onPullDownRefresh() {
			this.currentPage = 1
			this.handlePulldown()
		},
		onReachBottom() {
			if ( this.loadmore ) return
			if ( this.commentLoadmore ) return
			if ( this.isLastPage ) {
				if ( this.comments.length == 0 && !this.commentIsLastPage ) {
					this.handleCommentPulldown()
				} else if ( this.comments.length > 0 && !this.commentIsLastPage ) {
					this.handleCommentLoadmore()
				}
			} else {
				this.handleLoadmore()
			}
		},
		methods: {
			jumpPage () {
				this.$refs.dialog.prompt({
					title: {
						color: this.skinColor.color_1,
						text: '跳转页码（仅支持以页码跳转的源）'
					},
					value: this.currentPage,
					type: 'number',
					test: '^([1-9][0-9]*){1,3}$',
					required: true,
					error: '请输入非零的正整数',
					placeholder: '请输入页数',
					options: {
						bgColor: this.skinColor.color_bg_2
					},
					success: async ret => {
						if ( ret.confirm ) {
							this.loading = true
							this.currentPage = parseInt(ret.form[0].value)
							this.nextUrl = ''
							this.isLastPage = false
							const res = await this.getList()
							this.nextUrl = res.data.nextUrl
							this.catalogs = res.data.list
							this.isLastPage = res.data.isLastPage
							this.loading = false
							this.handleSaveRecord()
							if ( this.isLastPage ){
								this.handleCommentPulldown()
							}
						}
					}
				})
			},
			handleCharacterClick (params) {
			},
			async getContext () {
				return await this.$store.dispatch('network/request',{
					name: 'context',
					url: this.params.contextUrl,
					source: this.source,
					data: this.params
				})
			},
			async getList (type) {
				const res = await this.$store.dispatch('network/request',{
					name: 'catalog',
					url: this.nextUrl || this.params.catalogUrl,
					source: this.source,
					data: Object.assign({}, this.params, {currentPage: this.currentPage})
				})
				let list, nextUrl, isLastPage
				if ( res.code == this.app.$config.ERR_OK ) {
					const isContained = type == 'loadmore' ? this.app.$utils.isContained(this.catalogs, res.data.list) : false
					list = isContained ? [] : res.data.list
					nextUrl = res.data.nextUrl
					isLastPage = isContained || res.data.isLastPage
				} else {
					list = []
					nextUrl = ''
					isLastPage = true
				}
				return {
					data: {list, nextUrl, isLastPage}
				}
			},
			async handlePulldown () {
				await this.handleGetDetail()
				this.characters = await this.handleGetCharacter()
				this.recomes = await this.handleGetRecome()
				const res = await this.getContext()
				this.params = Object.assign({}, this.params, res.data?.data || {})
				this.nextUrl = ''
				this.isLastPage = false
				const res2 = await this.getList()
				this.nextUrl = res2.data.nextUrl
				this.catalogs = res2.data.list
				this.isLastPage = res2.data.isLastPage
				uni.stopPullDownRefresh()
				this.handleSaveRecord()
				if ( this.isLastPage ){
					this.handleCommentPulldown()
				}
				if ( this.currentPage > 1 ){
					this.$nextTick(function () {
						setTimeout(() => {
							uni.pageScrollTo({
								selector: '.more_content',
								duration: 0,
								complete: () => { this.loading = false }
							})
						}, 500)
					})
				} else this.loading = false
			},
			async handleLoadmore () {
				this.loadmore = true
				this.currentPage++
				const res = await this.getList('loadmore')
				this.loadmore = false
				this.nextUrl = res.data.nextUrl || ''
				this.catalogs = this.catalogs.concat(res.data.list)
				this.isLastPage = res.data.isLastPage
				if ( res.data.list.length == 0 ) this.currentPage--
				this.handleSaveRecord()
				if ( this.isLastPage && !this.commentIsLastPage ) {
					if ( this.comments.length == 0 ) this.handleCommentPulldown()
					else this.handleCommentLoadmore()
				}
			},
			handleSaveRecord () {
				if ( this.$store.getters['app/getHistory'] ) {
					this.$store.dispatch('resource/save', this.params)
					this.$store.dispatch('record/save', {
						id: this.id,
						current: this.currentPage
					})
				}
			},
			copyTo (str) {
				uni.setClipboardData({
				    data: str,
				    success: () => {
						uni.showToast({
							title: '复制内容成功',
							icon: 'none'
						})
				    },
					fail: () => {
						uni.showToast({
							title: '复制内容失败',
							icon: 'none'
						})
					}
				});
			},
			previewImage (src) {
				this.app.$business.previewImage({
					urls: [src]
				})
			},
			convertHTML (html) {
				html = html.replace(/\n/g, '<br/>')
				html = html.replace(/\r/g, '<br/>')
				const document = new HTMLParser(html.trim())
				const iframes = document.getElementsByTagName('iframe')
				iframes.forEach((iframe, key) => {
					let newIframe = iframe.outerHTML.trim()
					newIframe = newIframe.replace('<iframe', '<iframe onload="iframeLoad(' + key + ')"')
					newIframe = newIframe.replace('<iframe', '<iframe id="uni_polymerize_iframe_' + key + '"')
					newIframe = newIframe.replace('<iframe', '<iframe sandbox="allow-scripts allow-same-origin"')
					html = html.replace(iframe.outerHTML.trim(), newIframe)
				})
				const imgs = document.getElementsByTagName('img')
				imgs.forEach(img => {
					const imgStr = `<img src="" data-src="${img.attributes.src}" class="content-img" onload="handleContentImgLoad(this)" onerror="handleContentImgError(this)" onclick="previewImg('${img.attributes.src}')" style="${img.attributes.style}">`
					html = html.replace(img.tagContent.trim(), imgStr)
				})
				return html
			}
		}
	}
</script>

<script lang="renderjs" type="module" module="community">
	export default {
		mounted () {
			window.iframeLoad = function (key) {
				let iframeWindow = window.frames['uni_polymerize_iframe_' + key].contentWindow
				iframeWindow.window.console.log = function () {}
				iframeWindow.window.console.warn = function () {}
				iframeWindow.window.console.error = function () {}
				iframeWindow.window.alert = function () {}
				iframeWindow.window.confirm = function () {}
			}
			window.previewImg = (src) => {
				// #ifndef H5
				this.$ownerInstance.callMethod('previewImage', src);
				// #endif
				// #ifdef H5
				this.previewImage(src);
				// #endif
			}
			window.handleContentImgLoad = function (e) {
				e.style.minHeight = '';
				e.style.border = 'none';
			}
			window.handleContentImgError = function (e) {
				if ( e.getAttribute('src') ) {
					e.setAttribute('data-src', e.getAttribute('src'))
					e.removeAttribute('src');
				}
			}
			// 全局监听scroll滚动事件
			window.addEventListener('scroll', this.throttle(() => {
			    this.lazyLoad();
			}, 100));
			// 初始化的时候执行一下加载图片的函数
			this.lazyLoad();
		},
		methods: {
			//节流
			throttle(fn, delay = 200) {
				let timer = null;
				return function () {
			       	if (timer) return;
			       	timer = window.setTimeout(() => {
					    fn.apply(this, arguments);
					    timer = null;
					}, delay);
				}
			},
			lazyLoad () {
				const imgs = document.querySelectorAll('img[data-src]');
				if (!imgs.length) return;
				imgs.forEach(img => {
					const rect = img.getBoundingClientRect();
					if (rect.top < window.innerHeight && rect.bottom > 0) {
				    	img.src = img.dataset.src;
				    	img.removeAttribute('data-src'); // 我们是通过img[data-src]查找所有img标签的，渲染后就删除data-src可减少forEach循环的计算成本
				    }
				})
			}
		}
	}
</script>

<style>
	.nav-bar-box {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		border-bottom-width: 2px;
		border-bottom-style: solid;
		z-index: 2;
	}
	.tags {
		margin-top: 20rpx;
	}
	.subtitle {
		margin: 20rpx 0;
	}
	.subtitle .text {
		font-size: 20rpx;
		margin-left: 5rpx;
	}
	
	.title-dot {
		width: 5rpx;
		height: 30rpx;
		margin-right: 20rpx;
	}
	
	.loadmore {
		padding: 30rpx 0;
	}
	
	.loading {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
	}
	
	.rd-community {
		padding: 0 30rpx;
		border-bottom-width: 1px;
		border-bottom-style: solid;
	}
	.rd-community .subtitle .cover {
		margin-right: 20rpx;
	}
	.rd-community .land {
		font-size: 24rpx;
	}
	.rd-community .subtitle .info .time {
		margin-top: 10rpx;
	}
	.rd-community .content {
		margin: 20rpx 0;
	}
	.rd-community .content img, .rd-community .content video, .rd-community .content iframe {
		max-width: 100%!important;
	}
	.rd-community .content .btn {
		font-size: 26rpx;
		border-bottom-width: 1px;
		border-bottom-style: solid;
		width: 104rpx;
		padding: 10rpx 0 5rpx 0;
	}
	.rd-community .content-text {
		font-size: 28rpx;
		line-height: 40rpx;
	}
	.rd-community .images .image {
		height: 120rpx;
		position: relative;
	}
	.rd-community .images .badge {
		font-size: 18rpx;
		position: absolute;
		right: 0;
		top: 0;
		padding: 5rpx 15rpx 5rpx 10rpx;
		border-bottom-left-radius: 10rpx;
		border-top-right-radius: 10rpx;
	}
	.comments {
		margin-top: 20rpx;
		padding: 30rpx;
	}
	.comments-none {
		padding: 10rpx 30rpx;
	}
	.comments .comment {
		margin-bottom: 10rpx;
	}
	.comments .comment-label {
		font-size: 28rpx;
	}
	.comments .comment-content {
		font-size: 28rpx;
	}
	.comment-more {
		margin-top: 10rpx;
	}
	.comment-more-text {
		font-size: 24rpx;
		margin-right: 10rpx;
	}
	
	.content-img {
		min-height: 400px;
		border: 1px solid #eee;
	}
</style>
